<template>
  <view class="dev1ce-page">
    <!-- 顶部导航 -->
    <Navbar title="重点电器管理" />

    <!-- 主要内容 -->
    <view class="content">
      <!-- 已选重点电器 -->
      <view class="section-title">
        <text class="title-text">已选重点电器</text>
      </view>

      <!-- 表格区域 -->
      <view class="table-container">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 错误状态 -->
        <view v-else-if="error" class="error-container">
          <text class="error-text">{{ error }}</text>
          <view class="retry-btn" @click="fetchDeviceList">重试</view>
        </view>

        <!-- 数据为空状态 -->
        <view v-else-if="deviceList.length === 0" class="empty-container">
          <text class="empty-text">暂无设备数据</text>
        </view>

        <!-- 正常数据显示 -->
        <view v-else>
          <!-- 表头 -->
          <view class="table-header">
            <view class="header-cell">
              <text class="header-text">监测设备</text>
            </view>
            <view class="header-cell">
              <text class="header-text">电器</text>
            </view>
            <view class="header-cell">
              <text class="header-text">公司</text>
            </view>
            <view class="header-cell">
              <text class="header-text">人员</text>
            </view>
            <view class="header-cell">
              <text class="header-text">状态</text>
            </view>
          </view>
          <!-- 表格内容 -->
          <view class="table-body">
            <view
              v-for="(item, index) in deviceList"
              :key="index"
              class="table-row"
              :class="{ 'row-striped': index % 2 === 1 }"
            >
              <view class="table-cell">
                <text class="cell-text">{{ item.deviceId }}</text>
              </view>
              <view class="table-cell">
                <text class="cell-text">{{ item.appliance }}</text>
              </view>
              <view class="table-cell">
                <text class="cell-text">{{ item.company }}</text>
              </view>
              <view class="table-cell">
                <text class="cell-text">{{ item.personnel }}</text>
              </view>
              <view class="table-cell">
                <text
                  class="status-text"
                  :class="{
                    'status-working': item.status === '工作中',
                    'status-not-working': item.status === '未工作',
                  }"
                >
                  {{ item.status }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部添加按钮 -->
    <view class="bottom-actions">
      <view class="add-btn" @click="handleAdd">添加</view>
    </view>

    <!-- 添加设备弹窗 -->
    <view v-if="showModal" class="modal-overlay" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-body">
          <!-- 区域设备 -->
          <view class="form-row">
            <text class="form-label">区域设备</text>
            <view class="form-input-container" @click="showAreaPicker = true">
              <view class="area-display">
                {{ formData.areaDevice }}
              </view>
              <image
                class="dropdown-icon"
                src="/static/img/components/arrow.png"
                mode="widthFix"
              />
            </view>
          </view>

          <!-- 电器类型 -->
          <view class="form-row">
            <text class="form-label">电器类型</text>
            <view
              class="form-input-container"
              @click="showAppliancePicker = true"
            >
              <view class="appliance-display">
                {{ formData.applianceType || '请选择电器类型' }}
              </view>
              <image
                class="dropdown-icon"
                src="/static/img/components/arrow.png"
                mode="widthFix"
              />
            </view>
          </view>

          <!-- 所属公司 -->
          <view class="form-row">
            <text class="form-label">所属公司</text>
            <input
              class="form-input"
              v-model="formData.company"
              placeholder="请输入所属公司"
              placeholder-class="input-placeholder"
            />
          </view>

          <!-- 管理人员 -->
          <view class="form-row">
            <text class="form-label">管理人员</text>
            <input
              class="form-input"
              v-model="formData.manager"
              placeholder="请输入所属管理人员"
              placeholder-class="input-placeholder"
            />
          </view>

          <!-- 联系电话 -->
          <view class="form-row">
            <text class="form-label">联系电话</text>
            <input
              class="form-input"
              v-model="formData.phone"
              placeholder="联系电话"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>

        <!-- 确定按钮 -->
        <view class="modal-footer">
          <view class="confirm-btn" @click="handleConfirm">确定</view>
        </view>
      </view>
    </view>

    <!-- 区域选择器 -->
    <tn-picker
      v-model:open="showAreaPicker"
      :data="areaPickerData"
      :model-value="areaValue"
      :immediate-change="false"
      :mask="true"
      :show-cancel="false"
      confirm-color="#1ec8e1"
      label-key="label"
      value-key="value"
      @confirm="onAreaConfirm"
    />

    <!-- 电器类型选择器 -->
    <tn-picker
      v-model:open="showAppliancePicker"
      :data="applianceOptions"
      :immediate-change="false"
      :mask="true"
      :show-cancel="false"
      confirm-color="#1ec8e1"
      label-key="label"
      value-key="value"
      @confirm="onApplianceConfirm"
    />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Navbar from '@/components/Navbar.vue';
import { createRequest } from '@/utils/request';

// 弹窗显示状态
const showModal = ref(false);

// 区域选择器相关
const showAreaPicker = ref(false);
const areaValue = ref([]);
const areaPickerData = ref([]);

// 电器类型选择器相关
const showAppliancePicker = ref(false);
const applianceOptions = ref([]);

// 表单数据
const formData = ref({
  areaDevice: '',
  applianceType: '',
  company: '',
  manager: '',
  phone: '',
});

// 设备列表数据
const deviceList = ref([]);
const loading = ref(false);
const error = ref('');

// 设置状态栏样式
onMounted(async () => {
  // 设置状态栏为深色背景，白色文字
  uni.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: '#172869',
  });

  // 初始化区域选择器数据
  await initAreaPickerData();

  // 获取设备列表数据
  fetchDeviceList();

  // 获取电器选项数据
  fetchApplianceOptions();
});

// 获取设备列表数据
const fetchDeviceList = async () => {
  loading.value = true;
  error.value = '';

  try {
    const result = await createRequest('/key-device/list');

    if (result.code === 200 && result.data) {
      // 转换API数据格式为页面需要的格式
      deviceList.value = result.data.map(item => ({
        deviceId: item.monitorDeviceName,
        appliance: item.deviceName,
        company: item.company,
        personnel: item.person,
        status: item.deviceStatus === 1 ? '工作中' : '未工作',
      }));
    } else {
      error.value = result.msg || '获取设备列表失败';
    }
  } catch (err) {
    console.error('获取设备列表失败:', err);
    error.value = err.message || '网络请求失败';
  } finally {
    loading.value = false;
  }
};

// 获取电器选项数据
const fetchApplianceOptions = async () => {
  try {
    const response = await createRequest('/devices');

    if (response.code === 200 && response.data) {
      applianceOptions.value = response.data.map(device => ({
        label: device.deviceName,
        value: device.id,
      }));
    }
  } catch (error) {
    console.error('获取电器选项数据失败:', error);
  }
};

// 初始化区域选择器数据
const initAreaPickerData = async () => {
  try {
    // 调用真实的API请求
    const response = await createRequest(
      '/region/getRegionHierarchyForKeyDevice'
    );

    // 验证响应数据
    if (
      response &&
      response.code === 200 &&
      response.data &&
      Array.isArray(response.data)
    ) {
      // 转换数据格式，将接口返回的数据转换为选择器需要的格式
      areaPickerData.value = response.data.map(item => ({
        label: item.regionName,
        value: item.id,
        children: item.child
          ? item.child.map(child => ({
              label: child.regionName,
              value: child.id,
              children: child.child
                ? child.child.map(grandChild => ({
                    label: grandChild.regionName,
                    value: grandChild.id,
                    children: grandChild.devices
                      ? grandChild.devices.map(device => ({
                          label: device.deviceName,
                          value: device.deviceId,
                        }))
                      : [],
                  }))
                : [],
            }))
          : [],
      }));
    } else {
      console.warn('接口返回数据格式异常:', response);
      areaPickerData.value = [];
    }
  } catch (error) {
    console.error('获取区域选择器数据失败:', error);
    areaPickerData.value = [];
  }
};

// 处理区域选择确认
const onAreaConfirm = (val, item) => {
  // 获取完整的区域路径标签
  const areaLabels = [];
  let currentLevel = areaPickerData.value;

  for (let i = 0; i < val.length; i++) {
    const value = val[i];
    const levelItem = currentLevel.find(item => item.value === value);
    if (levelItem) {
      areaLabels.push(levelItem.label);
      currentLevel = levelItem.children || [];
    }
  }

  // 设置选中的区域设备，使用分隔符连接
  formData.value.areaDevice = areaLabels.join(' - ');
  areaValue.value = val;
  showAreaPicker.value = false;

  console.log('选择的区域路径:', areaLabels);
  console.log('区域值:', val);
};

// 处理电器类型选择确认
const onApplianceConfirm = (value, pickerItem) => {
  // 根据设备ID获取设备名称
  const selectedAppliance = applianceOptions.value.find(
    option => option.value === value
  );
  if (selectedAppliance) {
    formData.value.applianceType = selectedAppliance.label;
  }
  showAppliancePicker.value = false;
};

// 处理添加按钮点击
const handleAdd = () => {
  showModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
  showModal.value = false;
  // 重置表单数据
  formData.value = {
    areaDevice: '',
    applianceType: '',
    company: '',
    manager: '',
    phone: '',
  };
  // 重置区域选择器
  areaValue.value = [];
  // 重置电器选择器
  showAppliancePicker.value = false;
};

// 处理确定按钮点击
const handleConfirm = async () => {
  // 表单验证
  if (!formData.value.areaDevice) {
    uni.showToast({
      title: '请选择区域设备',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.applianceType) {
    uni.showToast({
      title: '请选择电器类型',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.company) {
    uni.showToast({
      title: '请输入所属公司',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.manager) {
    uni.showToast({
      title: '请输入管理人员',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.phone) {
    uni.showToast({
      title: '请输入联系电话',
      icon: 'none',
    });
    return;
  }

  try {
    // 提取设备ID（第四级）和三级区域ID（第三级）
    const monitorDeviceId = areaValue.value[3]; // 设备ID
    const secondLevelRegionId = areaValue.value[2]; // 三级区域ID

    // 获取电器类型ID
    const selectedAppliance = applianceOptions.value.find(
      option => option.label === formData.value.applianceType
    );
    const deviceName = selectedAppliance ? selectedAppliance.value : '';

    // 调用添加重点设备接口
    const response = await createRequest('/key-device/report', {
      method: 'post',
      data: {
        thirdLevelRegionId: secondLevelRegionId,
        monitorDeviceId: monitorDeviceId,
        deviceName: deviceName,
        company: formData.value.company,
        person: formData.value.manager,
        mobile: formData.value.phone,
      },
    });

    if (response && response.code === 200) {
      console.log('重点设备添加成功:', response);
      // 关闭弹窗
      closeModal();
      // 重新获取设备列表
      await fetchDeviceList();
    } else {
      console.error('重点设备添加失败:', response);
      uni.showToast({
        title: response?.msg || '添加失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('添加重点设备请求失败:', error);
    uni.showToast({
      title: '网络请求失败',
      icon: 'none',
    });
  }
};
</script>

<style scoped lang="scss">
.dev1ce-page {
  @include page-with-header;
  min-height: 100vh;
  background: #172869;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 30rpx;
}

.section-title {
  margin-bottom: 30rpx;
}

.title-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.table-container {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 20rpx;
  overflow: hidden;
  min-height: 200rpx;
}

.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 30rpx;
  min-height: 200rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #50daff;
  text-align: center;
}

.error-text {
  font-size: 28rpx;
  color: #ff6b6b;
  text-align: center;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
}

.retry-btn {
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 28rpx;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  margin-top: 20rpx;

  &:active {
    transform: scale(0.98);
  }
}

.table-header {
  display: flex;
  background: rgba(255, 255, 255, 0.08);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.header-cell {
  flex: 1;
  padding: 24rpx 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:first-child {
    flex: 0.8;
  }

  &:last-child {
    flex: 0.8;
  }
}

.header-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
  text-align: center;
}

.table-body {
  max-height: 600rpx;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.05);

  &:last-child {
    border-bottom: none;
  }

  &.row-striped {
    background: rgba(255, 255, 255, 0.02);
  }
}

.table-cell {
  flex: 1;
  padding: 24rpx 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:first-child {
    flex: 0.8;
  }

  &:last-child {
    flex: 0.8;
  }
}

.cell-text {
  font-size: 28rpx;
  color: #fff;
  text-align: center;
  word-break: break-all;
}

.status-text {
  font-size: 28rpx;
  font-weight: 500;
  text-align: center;

  &.status-working {
    color: #4fd2ff;
  }

  &.status-not-working {
    color: #ff4757;
  }
}

.bottom-actions {
  width: 100%;
  height: 168rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.add-btn {
  width: 686rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(58, 108, 255, 0.12);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    transform: scale(0.98);
  }
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 600rpx;
  background: #1a2a5a;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
}

.modal-body {
  padding: 30rpx;
  padding-top: 80rpx;
  box-sizing: border-box;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  width: 160rpx;
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

.form-input-container {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
  cursor: pointer;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  border-radius: 12rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  min-width: 0; /* 确保flex子元素可以收缩 */
  overflow: hidden; /* 防止内容溢出 */

  &:active {
    opacity: 0.8;
  }

  &:focus-within {
    border-color: #3a8dde;
  }
}

.area-display,
.appliance-display {
  flex: 1;
  font-size: 28rpx;
  color: #fff;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0; /* 确保flex子元素可以收缩 */
  max-width: calc(100% - 44rpx); /* 为箭头预留空间 (24rpx + 20rpx) */
  padding-right: 10rpx; /* 与箭头保持一定距离 */
}

.area-display {
  // 当元素为空时，显示提示文本
  &:empty::before {
    content: '请选择区域设备';
    color: rgba(185, 185, 185, 0.5);
  }
}

.appliance-display {
  // 当元素为空时，显示提示文本
  &:empty::before {
    content: '请选择电器类型';
    color: rgba(185, 185, 185, 0.5);
  }
}

.form-input {
  flex: 1;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #fff;
  box-sizing: border-box;

  &:focus {
    border-color: #3a8dde;
    outline: none;
  }
}

.input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.dropdown-icon {
  width: 24rpx;
  height: 14rpx;
  flex-shrink: 0; /* 防止箭头被压缩 */
  display: inline-block;
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1; /* 确保箭头在文本之上 */
}

.modal-footer {
  padding: 20rpx 30rpx 40rpx;
  display: flex;
  justify-content: center;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

/* Picker组件样式 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-picker__content) {
  background: #172869 !important;
  border-radius: 20rpx 20rpx 0 0 !important;
}

:deep(.tn-picker__header) {
  background: #172869 !important;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.tn-picker__confirm) {
  color: #1ec8e1 !important;
}

:deep(.tn-picker__cancel) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.tn-picker__title) {
  color: #fff !important;
}

:deep(.tn-picker-view__item) {
  color: #fff !important;
}

:deep(.tn-picker-view__item--selected) {
  color: #1ec8e1 !important;
}
</style>
